package com.fit.pages;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.fit.interfaces.User;
import com.fit.pages.Registration;
import com.fit.service.Security;
import com.fit.service.Users;

public class Login {
	
	private String userName;
	
	@Property
	private String password;
	
	@Inject
	@Property
	private Users users;
	
	@SessionState
	private User user;
	
	@Component(id="loginForm")
	private Form loginForm;
	
	@Inject
	private Messages messages;
	
	public String getUserName() {
		return userName;
	}

	

	public void setUserName(String userName) {
		this.userName = userName;
	}

	
	void onValidate(){
		User authenticatedUser = Security.authenticate(userName, password, users);
		if(authenticatedUser != null){
			user = authenticatedUser;
		}else{
			loginForm.recordError(messages.get("authentication-failed"));
		}
	}
	


	@OnEvent
	Object onSubmit(){
		System.out.println("form was submited");
		Class nextPage = null;
		User authenticatedUser = Security.authenticate(userName, password, users);
		if(authenticatedUser != null){
			user = authenticatedUser;
			nextPage = Index.class;
		} else {
		
		nextPage = Registration.class;
		}
		return nextPage;
	}
}
